import React, { Component } from "react";
import { Button, Input, Table, Divider, Popconfirm, message } from "antd";
import { connect } from "dva";
import moment from "moment";
import AddApplication from "./components/AddApplication";
import styles from "./ApplicationManagement.less";

const { Search } = Input;

@connect(stores => ({
  appListData: stores.appListData,
  userData: stores.user
}))
class ApplicationManagement extends Component {
  state = {
    appId: "",
    searchContent: "",
    pageNum: 1,
    pageSize: 10,
    ascOrDesc: "desc",
    modalVisible: false
  };

  componentDidMount() {
    this.init();
  }

  init = () => {
    this.setState({ pageNum: 1 });
    this.getAppList();
  };

  getAppList = () => {
    const { dispatch } = this.props;
    const { pageSize, pageNum, searchContent, ascOrDesc } = this.state;
    dispatch({
      type: "appListData/getAppList",
      payload: {
        pageNum,
        pageSize,
        appName: searchContent,
        ascOrDesc
      }
    });
  };

  deleteApp = appId => {
    const { dispatch } = this.props;
    dispatch({ type: "appListData/deleteApp", payload: { appId } }).then(
      res => {
        if (res.success) {
          this.getAppList();
        } else {
          message.error(`删除失败${res.errMsg}`);
        }
      }
    );
  };

  openModal = appId => {
    this.setState({ modalVisible: true, appId });
  };

  closeModal = () => {
    const { dispatch } = this.props;
    this.setState({ modalVisible: false });
    dispatch({
      type: "appListData/clearDetail"
    });
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    this.setState(
      {
        pageNum: Number(current),
        pageSize: Number(pageSize),
        ascOrDesc: sorter.order ? sorter.order.slice(0, -3) : ""
      },
      () => {
        this.getAppList();
      }
    );
  };

  handleSearch = e => {
    this.setState(
      {
        pageNum: 1,
        searchContent: e
      },
      () => {
        this.getAppList();
      }
    );
  };

  handleClear = e => {
    if (e.target.value === "") {
      this.setState({
        searchContent: ""
      });
    }
  };

  render() {
    const {
      appListData: { appList = [], totalCount = 0, loading = true } = {}
    } = this.props;
    const { pageNum, modalVisible, appId } = this.state;
    const columns = [
      {
        title: "应用名称",
        dataIndex: "appName",
        render: text => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden"
            }}
          >
            {text}
          </span>
        )
      },
      {
        title: "应用描述",
        dataIndex: "appDes",
        render: text => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden"
            }}
          >
            {text}
          </span>
        )
      },
      {
        title: "管理员",
        dataIndex: "owner",
        render: text =>
          text && JSON.parse(text) && JSON.parse(text).length > 0
            ? JSON.parse(text)[0].name
            : "-"
      },
      {
        title: "归属部门",
        dataIndex: "ownerDeptName"
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        sorter: true,
        defaultSortOrder: "descend",
        render: (text, record) =>
          moment(record.createTime).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        title: "操作",
        dataIndex: "operate",
        render: (text, record) => (
          // {
          // const {
          //   userData: {
          //     userInfo: { userId }
          //   }
          // } = this.props;
          // const { key } =
          //   (record.owner &&
          //     JSON.parse(record.owner) &&
          //     JSON.parse(record.owner)[0]) ||
          //   {};
          // return (
          <span>
            <a
              disabled={!record.dataPrivilege}
              onClick={() => this.openModal(record.appId)}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title={`你是否要删除${record.appName}?`}
              onConfirm={() => this.deleteApp(record.appId)}
              okText="确定"
              cancelText="取消"
              placement="topRight"
            >
              <a disabled={!!record.referencedNum || !record.dataPrivilege}>
                删除
              </a>
            </Popconfirm>
          </span>
        )
        // );
        // }
      }
    ];
    return (
      <div className={styles.root}>
        <div className={styles.topSelect}>
          <AddApplication
            visible={modalVisible}
            onCancel={this.closeModal}
            appId={appId}
            init={this.init}
          />
          <Button
            type="primary"
            style={{ fontSize: 14 }}
            onClick={() => this.openModal()}
          >
            创建应用
          </Button>
          <div style={{ color: "rgba(0,0,0,0.85)" }}>
            <Search
              onSearch={this.handleSearch}
              onChange={this.handleClear}
              placeholder="请输入应用名称"
              style={{ width: 272 }}
              allowClear
            />
          </div>
        </div>
        <Table
          rowKey={record => record.appId}
          size="middle"
          columns={columns}
          dataSource={appList}
          onChange={(e, filters, sorter) =>
            this.handleTableChange(e, filters, sorter)
          }
          loading={loading}
          locale={{ emptyText: "暂无数据！" }}
          pagination={{
            defaultPageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            current: pageNum,
            total: totalCount,
            showTotal: total => `共有 ${total} 条`
          }}
        />
      </div>
    );
  }
}

export default ApplicationManagement;
